<template>
  <div class="product-config-container">
    <a-card class="main-card">
      <template #title>
        <div class="card-title">
          <span>商品配置</span>
        </div>
      </template>

      <!-- 操作按钮区域 -->
      <div class="action-header">
        <a-button type="primary" @click="handleAdd">
          添加商品
        </a-button>
      </div>

      <!-- 添加商品弹窗 -->
      <a-modal
        v-model:visible="addModalVisible"
        title="添加商品"
        @ok="handleAddSubmit"
        @cancel="resetAddForm"
        :confirmLoading="false"
      >
        <a-form :model="addForm" :rules="rules">
          <a-form-item label="商品" name="productId">
            <a-select 
              v-model:value="addForm.productId" 
              placeholder="请选择商品"
              :loading="productLoading"
            >
              <a-select-option v-for="product in allProducts" :key="product.productId" :value="product.productId">
                {{ product.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="模板" name="templateId">
            <a-select 
              v-model:value="addForm.templateId" 
              placeholder="请选择模板"
              :loading="templateLoading"
            >
              <a-select-option v-for="template in templateList" :key="template.id" :value="template.id">
                {{ template.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="价格" name="price">
            <a-input-number v-model:value="addForm.price" :min="0" :precision="2" style="width: 100%" />
          </a-form-item>
        </a-form>
      </a-modal>

      <!-- 商品列表区域 -->
      <div class="product-list">
        <a-table
          :columns="columns"
          :data-source="productList"
          :loading="productLoading"
          :pagination="false"
          row-key="productId"
          class="custom-table"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'image'">
              <img :src="record.imageUrlList[0]" class="product-image" v-if="record.imageUrlList && record.imageUrlList.length > 0" />
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a-button type="link" @click="handleChangeTemplate(record)">更改模板</a-button>
                <a-button type="link" danger @click="handleDelete(record)">删除</a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </a-card>

    <!-- 更改模板弹窗 -->
    <a-modal
      v-model:visible="changeTemplateModalVisible"
      title="更改模板"
      @ok="handleChangeTemplateSubmit"
      @cancel="resetChangeTemplateForm"
      :confirmLoading="changeTemplateLoading"
    >
      <a-form :model="changeTemplateForm" :rules="changeTemplateRules">
        <a-form-item label="模板" name="templateId">
          <a-select 
            v-model:value="changeTemplateForm.templateId" 
            placeholder="请选择模板"
            :loading="templateLoading"
          >
            <a-select-option v-for="template in templateList" :key="template.id" :value="template.id">
              {{ template.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import * as storeApi from '@/api/store';
import { listAllProduct, changeProductTemplate } from '@/api/product';
import { getStoreTemplate } from '@/api/template';
import { useStoreMsgStore } from '@/store/useStoreMsgStore';

interface Store {
  storeId: string;
  storeName: string;
  address: string;
  phone: string;
  openingHours: string;
  status: number;
  coverImage: string;
}

interface Product {
  productId: number;
  name: string;
  description: string;
  category_id: number;
  imageUrlList: string[];
  basePrice: number;
  sort: number;
  create_time: string;
  update_time: string;
  templateId: number;
  templateName: string;
}

interface Category {
  categoryId: number;
  categoryName: string;
  productList: Product[];
}

interface ApiResponse<T> {
  code: number;
  msg: string;
  data: T;
}

// 获取当前门店信息
const storeMsg = useStoreMsgStore();

// 商品相关数据
const productList = ref<Product[]>([]);
const productLoading = ref(false);

// 添加商品相关数据
const addModalVisible = ref(false);
const addForm = ref({
  productId: undefined as number | undefined,
  templateId: undefined as number | undefined,
  price: '',
});

// 商品和模板列表数据
const allProducts = ref<any[]>([]);
const templateList = ref<any[]>([]);
const templateLoading = ref(false);

// 添加商品表单规则
const rules = {
  productId: [{ required: true, message: '请选择商品' }],
  templateId: [{ required: true, message: '请选择模板' }],
  price: [{ required: true, message: '请输入价格' }],
};

// 表格列定义
const columns = [
  {
    title: '商品图片',
    dataIndex: 'imageUrlList',
    key: 'image',
    width: 100,
  },
  {
    title: '商品名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '商品描述',
    dataIndex: 'description',
    key: 'description',
  },
  {
    title: '价格',
    dataIndex: 'basePrice',
    key: 'price',
  },
  {
    title: '模板名称',
    dataIndex: 'templateName',
    key: 'templateName',
  },
  {
    title: '更新时间',
    dataIndex: 'update_time',
    key: 'update_time',
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
  },
];

// 加载门店商品列表
const loadProductList = async () => {
  if (!storeMsg.storeId) return;
  
  productLoading.value = true;
  try {
    const response = await storeApi.listStoreProduct(storeMsg.storeId);
    if (response.data.code === 200) {
      // 将所有分类下的商品合并到一个数组中
      const allProducts: Product[] = [];
      response.data.data.forEach((category: Category) => {
        allProducts.push(...category.productList);
      });
      productList.value = allProducts;
    } else {
      message.error(response.data.msg || '加载商品列表失败');
    }
  } catch (error) {
    console.error('加载商品列表失败:', error);
    message.error('加载商品列表失败');
  } finally {
    productLoading.value = false;
  }
};

// 加载所有商品列表
const loadAllProducts = async () => {
  productLoading.value = true;
  try {
    const response = await listAllProduct(100, 1);
    if (response.data.code === 200) {
      allProducts.value = response.data.data.list || [];
    } else {
      message.error(response.data.msg || '加载商品列表失败');
    }
  } catch (error) {
    console.error('加载商品列表失败:', error);
    message.error('加载商品列表失败');
  } finally {
    productLoading.value = false;
  }
};

// 加载模板列表
const loadTemplateList = async () => {
  if (!storeMsg.storeId) return;
  
  templateLoading.value = true;
  try {
    const response = await getStoreTemplate(storeMsg.storeId, '', 1, 100);
    if (response.data.code === 200) {
      templateList.value = response.data.data.list || [];
    } else {
      message.error(response.data.msg || '加载模板列表失败');
    }
  } catch (error) {
    console.error('加载模板列表失败:', error);
    message.error('加载模板列表失败');
  } finally {
    templateLoading.value = false;
  }
};

// 更改模板相关数据
const changeTemplateModalVisible = ref(false);
const changeTemplateLoading = ref(false);
const changeTemplateForm = ref({
  productId: undefined as number | undefined,
  templateId: undefined as number | undefined,
});

// 更改模板表单规则
const changeTemplateRules = {
  templateId: [{ required: true, message: '请选择模板' }],
};

// 处理更改模板
const handleChangeTemplate = (record: Product) => {
  changeTemplateForm.value = {
    productId: record.productId,
    templateId: record.templateId,
  };
  changeTemplateModalVisible.value = true;
  loadTemplateList();
};

// 提交更改模板
const handleChangeTemplateSubmit = async () => {
  if (!storeMsg.storeId) {
    message.warning('请先选择门店');
    return;
  }
  
  try {
    // 表单验证
    if (!changeTemplateForm.value.templateId) {
      message.warning('请选择模板');
      return;
    }

    const response = await changeProductTemplate(
      storeMsg.storeId,
      Number(changeTemplateForm.value.productId),
      Number(changeTemplateForm.value.templateId)
    );
    
    if (response.data.code === 200) {
      message.success('更改模板成功');
      changeTemplateModalVisible.value = false;
      resetChangeTemplateForm();
      loadProductList();
    } else {
      message.error(response.data.msg || '更改模板失败');
    }
  } catch (error) {
    console.error('更改模板失败:', error);
    message.error('更改模板失败');
  }
};

// 重置更改模板表单
const resetChangeTemplateForm = () => {
  changeTemplateForm.value = {
    productId: undefined,
    templateId: undefined,
  };
};

// 删除商品
const handleDelete = (record: any) => {
  // TODO: 实现删除功能
  console.log('删除商品:', record);
};

// 处理添加商品
const handleAdd = () => {
  addModalVisible.value = true;
  loadAllProducts();
  loadTemplateList();
};

// 提交添加商品
const handleAddSubmit = async () => {
  if (!storeMsg.storeId) {
    message.warning('请先选择门店');
    return;
  }
  
  try {
    // 表单验证
    if (!addForm.value.productId) {
      message.warning('请选择商品');
      return;
    }
    if (!addForm.value.templateId) {
      message.warning('请选择模板');
      return;
    }
    if (!addForm.value.price) {
      message.warning('请输入价格');
      return;
    }

    const response = await storeApi.bindProduct({
      storeId: storeMsg.storeId,
      productId: Number(addForm.value.productId),
      templateId: Number(addForm.value.templateId),
      price: String(addForm.value.price),
    });
    
    if (response.data.code === 200) {
      message.success('添加商品成功');
      addModalVisible.value = false;
      resetAddForm();
      loadProductList();
    } else {
      message.error(response.data.msg || '添加商品失败');
    }
  } catch (error) {
    console.error('添加商品失败:', error);
    message.error('添加商品失败');
  }
};

// 重置添加表单
const resetAddForm = () => {
  addForm.value = {
    productId: undefined,
    templateId: undefined,
    price: '',
  };
};

// 页面加载时获取商品列表
onMounted(() => {
  loadProductList();
});
</script>

<style scoped>
.product-config-container {
  padding: 24px;
}

.main-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.card-title {
  font-size: 18px;
  font-weight: 500;
  color: #1f1f1f;
}

.action-header {
  margin-bottom: 24px;
}

.product-list {
  margin-top: 16px;
}

.custom-table {
  margin-top: 16px;
}

.product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 500;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: #f5f5f5;
}

:deep(.ant-btn-link) {
  padding: 4px 8px;
}

:deep(.ant-tag) {
  margin: 0;
}
</style> 